#!/usr/bin/env python  
#coding=utf-8  
import tkinter as tk
from tkinter import *
from  tkinter  import ttk
import tkinter.messagebox as messagebox#这个是消息框，对话框的关键
import windnd
from Sort import *
import os


# 可视化窗体类
class mainform:
    def __init__(self):
        self.bg = "#363636"
        self.root = tk.Tk()

        # with open('tmp.ico','wb') as tmp:
        #     tmp.write(base64.b64decode(Icon().img))
        #     self.root.iconbitmap('tmp.ico')
        # os.remove('tmp.ico')

        # self.root.wm_iconbitmap('favicon.ico')
        self.root.title("寻图片像素点差异工具")
        # 设置窗体大小不可变
        self.root.resizable(width=False, height=False)
        #让窗体显示在屏幕中央
        self.root.resizable(False,False)
        self.root.update() # update window ,must do
        curWidth = 402 # get current width
        curHeight = 350 # get current height
        scnWidth,scnHeight = self.root.maxsize() # get screen width and height
        # now generate configuration information
        tmpcnf = '%dx%d+%d+%d'%(curWidth,curHeight,
        (scnWidth-curWidth)/2,(scnHeight-curHeight)/2)
        self.root.geometry(tmpcnf)
        # self.root.configure(background = self.bg)

        # 记录图像文件地址
        self.SocueFilePath = ""
        self.DiffFilePath = ""

        # 记录差异的像素点位置
        self.DiffPixelList = []
        
        # 初始化图像数据分析类
        self.Sort = ImgDataProcess()

    def form(self):
        # # 左边日志标签
        # self.LeftLogText = tk.StringVar() 
        # self.LeftLog_lab = Label(self.root,textvariable=self.LeftLogText, font=('宋体', 16, "bold"),fg='#A52A2A')
        # self.LeftLog_lab.place(x=0,y=5+155)
        # self.LeftLogText.set("  (✿◠‿◠)")        
        # # 右边日志标签
        # self.RightLogText = tk.StringVar() 
        # self.RightLog_lab = Label(self.root,textvariable=self.RightLogText, font=('宋体', 16, "bold"),fg='#A52A2A')
        # self.RightLog_lab.place(x=275,y=5+155)
        # self.RightLogText.set(" (๑￫‿ฺ￩๑)")

        # 源图像数据文件路径容器框
        self.SoucePathLabelFrame = LabelFrame(self.root,text="将源图像数据文件拖入输入框",font=('宋体', 10),fg='#D02090',padx=2,pady=2)
        self.SoucePathLabelFrame.place(x=3,y=5)
        #源图像数据文件路径地址输入框
        self.SoucePathText = Text(self.SoucePathLabelFrame,font=('宋体',15,'bold'),width=35,height=5,bg='#FAEBD7',fg='#D02090',state='normal')            
        self.SoucePathText.grid(row=0,column=0)
        self.SoucePathText.insert('1.0'," **请将要源图像数据.h文件拖入此处**")		#将获取到的文件地址输入文本框
        self.SoucePathText['state'] = 'disable'
    
        # 差异图像数据文件路径容器框
        self.DiffPathLabelFrame = LabelFrame(self.root,text="将差异图像数据文件输入框",font=('宋体', 10),fg='#000080',padx=2,pady=2)
        self.DiffPathLabelFrame.place(x=3,y=180)
        #差异图像数据文件路径地址输入框
        self.DiffPathText = Text(self.DiffPathLabelFrame,font=('宋体',15,'bold'),width=35,height=5,bg='#CDB5CD',fg='#000080',state='normal')            
        self.DiffPathText.grid(row=0,column=0)
        self.DiffPathText.insert('1.0',"**请将要差异图像数据.h文件拖入此处**")		#将获取到的文件地址输入文本框
        self.DiffPathText['state'] = 'disable'

        #拖拽文件
        windnd.hook_dropfiles(self.SoucePathText ,func=self.dragged_Socuefiles)        #拖拽文件至源图像路径输入框
        windnd.hook_dropfiles(self.DiffPathText ,func=self.dragged_Difffiles)         #拖拽文件至差异图像路径输入框

        # # 路径交换按钮
        self.PathSwapButton = Button(self.root,text="↑↓路径交换↑↓",font=("宋体",18,"bold"),background='#EE7942',state='normal',command=self.PathSwapButton_Func)#
        self.PathSwapButton.place(x=90,y=132)

        
        # # 合成按钮
        self.CreateButton = Button(self.root,text="合成",font=("宋体",18,"bold"),background='#008B8B',state='normal',command=self.CreateButton_Func)
        self.CreateButton.place(x=300,y=306)
    
    #拖拽文件获取路径
    def dragged_Socuefiles(self,files):
        msg = '\n'.join((item.decode('gbk')for item in files))
        record = msg.split("\n")
        if len(record) > 1:			#说明加载了不止一个pdf文件
            messagebox.showinfo("提示！","请单个拖入文件！") 	#弹框提示
        else:						#单独拖入一个PDF文件时才执行文本框填写和转换	
            if self.SocueTextBox(msg):
                self.SocueFilePath = msg

        #文本框
    def SocueTextBox(self,filespath):
        self.SoucePathText['state'] = 'normal'
        self.SoucePathText.delete("1.0",END)			#清空上次文本框
        self.SoucePathText.insert('1.0',filespath)		#将获取到的文件地址输入文本框
        self.SoucePathText['state'] = 'disable'
        print(filespath)
        print(os.path.splitext(filespath))
        return True
        

    #拖拽文件获取路径
    def dragged_Difffiles(self,files):
        msg = '\n'.join((item.decode('gbk')for item in files))
        record = msg.split("\n")
        if len(record) > 1:			#说明加载了不止一个pdf文件
            messagebox.showinfo("提示！","请单个拖入文件！") 	#弹框提示
        else:						#单独拖入一个PDF文件时才执行文本框填写和转换	
            if self.DiffTextBox(msg):
                self.DiffFilePath = msg

        #文本框
    def DiffTextBox(self,filespath):
        self.DiffPathText['state'] = 'normal'
        self.DiffPathText.delete("1.0",END)			#清空上次文本框
        self.DiffPathText.insert('1.0',filespath)		#将获取到的文件地址输入文本框
        self.DiffPathText['state'] = 'disable'
        print(filespath)
        print(os.path.splitext(filespath)[0])
        return True


    def PathSwapButton_Func(self):         
        # 交换地址
        Temp = self.SocueFilePath
        self.SocueFilePath = self.DiffFilePath
        self.DiffFilePath = Temp
        # 填写地址到输入框
        self.SocueTextBox(self.SocueFilePath)
        self.DiffTextBox(self.DiffFilePath)

    def CreateButton_Func(self):
        if self.SocueFilePath =="" or self.DiffFilePath == "":
            print("输入框存在空路径")
            messagebox.showinfo("告警","输入框存在空路径!")
            return
        
        # 打开文件并逐行读取文件内容
        SouceData = self.Sort.ReadImgFile(self.SocueFilePath)
        DiffData = self.Sort.ReadImgFile(self.DiffFilePath)

        # 输入第一行数据，分析图像信息
        self.Sort.SouceImgName,self.Sort.SouceImgInfo_Scan,self.Sort.SouceImgInfo_Gray,self.Sort.SouceImgInfo_Width,self.Sort.SouceImgInfo_Height,self.Sort.SouceImgInfo_RGBMode,self.Sort.SouceImgInfo_RGB = self.Sort.ReadImgInfo(SouceData[0])
        self.Sort.DiffImgName,self.Sort.DiffImgInfo_Scan,self.Sort.DiffImgInfo_Gray,self.Sort.DiffImgInfo_Width,self.Sort.DiffImgInfo_Height,self.Sort.DiffImgInfo_RGBMode,self.Sort.DiffImgInfo_RGB = self.Sort.ReadImgInfo(DiffData[0])

        # 将各行数据按照","分割
        SouceDataSplit=[i.split(",") for i in SouceData]
        DiffDataSplit=[i.split(",") for i in DiffData]

        self.DiffPixelList = self.Sort.CompareImg(SouceDataSplit,DiffDataSplit,self.Sort.SouceImgInfo_Width,self.Sort.SouceImgInfo_Height)

        self.WritePixelposition(self.DiffPixelList)

    
    # 文件生成和保存
    def WritePixelposition(self,DiffPixelData):
        filepath = self.Sort.DiffImgName+".h"
        writeFile = open(filepath,"w+",encoding="utf-8")

        # 差异像素点数组名字符串
        DiffPixelStr = "const unsigned int "+self.Sort.DiffImgName+"[%d][2] = {"%len(DiffPixelData)

        # 写第一行数据
        writeFile.write(DiffPixelStr)
        
        # 循环写入数据
        for PixelCount in range(0,len(DiffPixelData)):
            # 每8个数据换行
            if int(PixelCount % 8) == 0:
                writeFile.write("\n")
            writeFile.write(DiffPixelData[PixelCount]+",")

        # 写最后一行数据
        writeFile.write("};")
        writeFile.close()



def run():
    m = mainform()
    m.form()
    mainloop()

if __name__ == "__main__":
    run()
